const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      rules: {
        Article_Name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
      },
      brand: [],
      category: [],
      series: [],
      item: [],
      unit: [],
      fileList: [],
      fileList1: [],
      fileList3: [],
      dialogImageUrl: '',
      dialogVisible: false,
      dialogVisible1: false,
      flag: true,
      num: '',
      form: {
        Article_SerialNumber: "",
        Article_Name: '',
        Brand_SerialNumber: '',
        Category_SerialNumber: '',
        Series_SerialNumber: '',
        Item_SerialNumber: '',
        Size: '',
        Unit_Price: '',
        Picture_URL: '',
        Weight: '',
        Weight_Unit: '',
        Package_Quantity: '',
        SKU_Package_Size: '',
        Carton_Quantity: '',
        Children: {
          article_pic: [],
          article_barcode: [],
          article_specifications: [
            {
              Article_Specifications_SerialNumber: '',
              Article_SerialNumber: '',
              Net_Content: '',  //净含量
              Unit_Price: '', //零售价
              Packing: '', //装箱数
              PackingSize: '', //装箱尺寸
              OutsidePackingSize: '', //外箱尺寸
              Specifications_Name: '', //规格说明
              Picture_URL: '',   //规格图片
              pic: ''
            }
          ]
        }
      },
      loading: false,
      is: true,
      is_xq: true,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogVisible1: false,
    }
  },
  mounted() {
    //获取数据
    const Article_SerialNumber = sessionStorage.getItem("Article_SerialNumber")
    console.log(Article_SerialNumber, $.cookie("token"))
    this.getData(Article_SerialNumber);
    //图片拖拽
    console.log(this.form.Children.article_pic);
    //主图
    var $ul = this.$el.querySelector('.upload_warp_img1')
    this.sortList = Sortable.create($ul, {
      handle: '.upload_warp_img_div1',
      draggable: ".upload_warp_img_div1",
      animation: 150,
      onUpdate: (event) => {
        var newIndex = event.newIndex,
          oldIndex = event.oldIndex
        $li = $ul.children[newIndex],
          $oldLi = $ul.children[oldIndex]
        // 先删除移动的节点
        $ul.removeChild($li)
        // 再插入移动的节点到原有节点，还原了移动的操作
        if (newIndex > oldIndex) {
          $ul.insertBefore($li, $oldLi)
        } else {
          $ul.insertBefore($li, $oldLi.nextSibling)
        }
        var item = this.form.Children.article_pic[event.oldIndex];
        this.form.Children.article_pic.splice(event.oldIndex, 1);
        this.form.Children.article_pic.splice(event.newIndex, 0, item);
      }
    })
    //详情图
    var $ul2 = this.$el.querySelector('.upload_warp_img')
    this.sortList = Sortable.create($ul2, {
      handle: '.upload_warp_img_div',
      draggable: ".upload_warp_img_div",
      animation: 150,
      onUpdate: (event) => {
        var newIndex = event.newIndex,
          oldIndex = event.oldIndex
        $li = $ul2.children[newIndex],
          $oldLi = $ul2.children[oldIndex]
        // 先删除移动的节点
        $ul2.removeChild($li)
        // 再插入移动的节点到原有节点，还原了移动的操作
        if (newIndex > oldIndex) {
          $ul2.insertBefore($li, $oldLi)
        } else {
          $ul2.insertBefore($li, $oldLi.nextSibling)
        }
        var item = this.form.Children.article_pic[event.oldIndex];
        this.form.Children.article_pic.splice(event.oldIndex, 1);
        this.form.Children.article_pic.splice(event.newIndex, 0, item);
        console.log(this.form.Children.article_pic);
      }
    })
  },
  methods: {
    //商品主图轮播图片
    uploadBanner(file) {
      let _this = this
      this.form.Children.article_pic.push({
        Article_PicNumber: "",
        Article_SerialNumber: this.form.Article_SerialNumber,
        Picture_Order: this.form.Children.article_pic.filter(item => item.Picture_Type == '0').length + 1,
        Picture_Type: '0',
        Picture_Url: '',
        pic: '',
      })
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  _this.$message(Result.Picture_Url)
                }
              },
              success: function (Result) {
                _this.form.Children.article_pic[_this.form.Children.article_pic.length - 1].pic = e.target.result
                if (Result.Status == "success") {
                  _this.form.Children.article_pic[_this.form.Children.article_pic.length - 1].Picture_Url = Result.Picture_Url;
                  _this.$message.success('上传成功')
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    //删除图片
    handleRemove(type, item) {
      if (type == "details") {
        this.handle(item)
      } else if (type == "banner") {
        this.handle(item)
      }
    },
    handle(item) {
      if (item.Picture_Type_Original) {
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            item.Row_Status = 1;
          })
          .catch(() => { });

      } else {
        this.form.Children.article_pic.splice(this.form.Children.article_pic.indexOf(item), 1);
      }
    },

    //查看图片
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      console.log(file);
      this.dialogImageUrl = file
    },
    //商品详情上传
    uploadDetails(file) {
      let _this = this
      this.form.Children.article_pic.push({
        Article_PicNumber: "",
        Article_SerialNumber: this.form.Article_SerialNumber,
        Picture_Order: this.form.Children.article_pic.filter(item => item.Picture_Type == 1).length + 1,
        Picture_Type: '1',
        Picture_Url: '',
        pic: '',
      })
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                _this.form.Children.article_pic[_this.form.Children.article_pic.length - 1].pic = e.target.result
                if (Result.Status == "success") {
                  _this.$message.success('上传成功')
                  _this.form.Children.article_pic[_this.form.Children.article_pic.length - 1].Picture_Url = Result.Picture_Url;
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    getData(Article_SerialNumber) {
      let _this = this;
      $.ajax({
        url: DomainName + '/getArticleInfoIDAction',
        type: 'POST',
        data: {
          Article_SerialNumber,
          token: $.cookie("token")
        },
        success: function (res) {
          _this.form = res.article_info[0]
          _this.num = _this.form.Children.article_specifications.length
          console.log(_this.form)
          _this.form.Children.article_pic.forEach(item => {
            item.srcList = []
            item.srcList.push(DomainIMG + item.Picture_Url)
          })
          _this.form.srcList = [DomainIMG + _this.form.Picture_URL]
          console.log(_this.form.Children.article_pic)
          _this.form.Children.article_pic.sort((a, b) => {
            //return( a[age] - b[age])
            return (a.Picture_Order - b.Picture_Order)
          })
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    handleSpecification(index) {
      this.Specification = index
      console.log(this.Specification);
    },
    // 提交订单
    submitForm() {
      let TypeNum1 = 0;
      let TypeNum2 = 0;
      this.form.Children.article_pic.forEach(item => {
        if (item.Picture_Type == '0') {
          TypeNum1++
          item.Picture_Order = TypeNum1;
        }
        if (item.Picture_Type == '1') {
          TypeNum2++
          item.Picture_Order = TypeNum2;
          console.log(item);
        }
      }
      )
      let _this = this;
      console.log(_this.form);
      _this.loading = true
      const { add, modify } = _this.deal()
      let data = {}
      if (add == null) {
        data = { Data: JSON.stringify({ Modify: { article_info: [modify] } }), token: $.cookie("token") }
      } else {
        data = {
          Data: JSON.stringify(
            {
              Modify: { article_info: [modify] },
              Add: { article_info: [add] }
            }
          ),
          token: $.cookie("token")
        }
      }
      $.ajax({
        url: DomainName + '/getEditAction',
        type: 'POST',
        data,
        success: function (res) {
          console.log('提交结果', res)
          _this.$message.success("提交成功")
          window.location.href = './goods.html'
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)
      let add_article_pic = [], modify_article_pic = []
      let add_article_barcode = [], modify_article_barcode = []
      let add_article_specifications = [], modify_article_specifications = []
      for (const i in modify.Children.article_pic) {
        const obj = modify.Children.article_pic[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_article_pic.push(obj)
        } else {
          modify_article_pic.push(obj)
        }
      }
      for (const i in modify.Children.article_barcode) {
        const obj = modify.Children.article_barcode[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_article_barcode.push(obj)
        } else {
          modify_article_barcode.push(obj)
        }
      }
      for (const i in modify.Children.article_specifications) {
        const obj = modify.Children.article_specifications[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_article_specifications.push(obj)
        } else {
          modify_article_specifications.push(obj)
        }
      }
      add.Children.article_pic = add_article_pic
      add.Children.article_barcode = add_article_barcode
      add.Children.article_specifications = add_article_specifications

      modify.Children.article_pic = modify_article_pic
      modify.Children.article_barcode = modify_article_barcode
      modify.Children.article_specifications = modify_article_specifications

      if (add_article_pic.length == 0 && add_article_barcode.length == 0 && add_article_specifications.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    // 商品规格图片
    Specifications(file) {
      let _this = this
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        num = 0.4
      } else if (file.size > 500000) {
        num = 0.2
      }
      console.log(file);
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            _this.form.Children.article_specifications[_this.Specification].pic = e.target.result
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                if (Result.Status == "success") {
                  _this.form.Children.article_specifications[_this.Specification].Picture_URL = Result.Picture_Url
                  _this.$message.success('上传成功')
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },

    add_article_specifications() {
      this.form.Children.article_specifications.push({
        Article_Specifications_SerialNumber: '',
        Article_SerialNumber: this.form.Article_SerialNumber,
        Net_Content: '',  //净含量
        Unit_Price: '', //零售价
        Packing: '', //装箱数
        PackingSize: '', //装箱尺寸
        OutsidePackingSize: '', //外箱尺寸
        Specifications_Name: '', //规格说明
        Picture_URL: '',
        pic: ''
      })
    },
    remove_article_specifications() {
      console.log(this.form.Children.article_specifications.length, this.num)

      if (this.num < this.form.Children.article_specifications.length) {
        this.form.Children.article_specifications.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
  }
})